package com.api.rc.config;

import com.api.rc.handler.LobbyWebSocketHandler;
import com.api.rc.interceptor.LobbyHandshakeInterceptor;
import com.api.rc.lobby.LobbyManager;
import com.api.rc.service.RapidChallengeService;
import com.api.user.service.UserInfoService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.*;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * @author RenQiang
 * @date 2021/7/17
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    private final LobbyManager lobbyManager;
    private final RapidChallengeService rapidChallengeService;
    private final UserInfoService userInfoService;

    public WebSocketConfig(LobbyManager lobbyManager, RapidChallengeService rapidChallengeService, UserInfoService userInfoService) {
        this.lobbyManager = lobbyManager;
        this.rapidChallengeService = rapidChallengeService;
        this.userInfoService = userInfoService;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(lobbyRoomHandler(), "/rc/lobby")
                .addInterceptors(lobbyHandshakeInterceptor())
                .setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler lobbyRoomHandler() {
        return new LobbyWebSocketHandler(lobbyManager, userInfoService);
    }

    @Bean
    public HandshakeInterceptor lobbyHandshakeInterceptor() {
        return new LobbyHandshakeInterceptor(rapidChallengeService);
    }
}
